import logo from "@/assets/logo.png";
import type { AppSettings, VueMetaEnv } from "@/types/index";
import type { RouteRecordRaw } from "vue-router";
import { defineComponent } from "vue";
import { pa } from "element-plus/es/locales.mjs";

/** 默认系统配置. */
const defaultSettings: AppSettings = reactive({
  title: "jmash-vue3",
  version: "v0.0.1",
  logo: logo,
  showSettings: true,
  tagsView: true,
  fixedHeader: true,
  sidebarLogo: true,
  layout: "left",
  theme: "light",
  size: "default",
  language: "zh-cn",
  themeColor: "#409EFF",
  watermarkEnabled: false,
  watermarkContent: "jmash-vue3",
});

/** 默认Vue MetaEnv 配置. */
const vueMetaEnv: VueMetaEnv = reactive({
  APP_PORT: "",
  APP_BASE_URL: "",
  APP_API_URL: "/",
  APP_BASE_API: "/",
  APP_CLIENT_ID: "pc_vue3",
  APP_WECHAT_APPID: "",
  APP_DIRECTORY_ID: "jmash",
  APP_TENANT: "",
  APP_ACTIVE: "user",
  APP_REDIRECT: "/",
  APP_TIMEOUT: 60000,
});

//动态菜单模块
const menus = new Map();
//动态路由模块
const dynamicRoutes: RouteRecordRaw[] = [];
//图片地址
let imageUrl = `${vueMetaEnv.APP_API_URL}v1/file/path/pc`;

//注册Layout
const Layout = () => import("./layout/index.vue");
menus.set("Layout", Layout);

//router
const modules = import.meta.glob("./views/**/**.vue");
addViteMenus(modules, 7);

/** 添加Vite模块菜单. **/
//const modules = import.meta.glob("./views/**/**.vue");
export function addViteMenus(modules: Record<string, any>, startLen: number) {
  for (const path in modules) {
    const pathName = path.substring(startLen, path.length - 4);
    menus.set(pathName, modules[path]);
  }
}

//注册组件
export function defineComponentWithName(component: any, name: string) {
  return defineComponent({
    name,
    render() {
      return h(component, this.$attrs, this.$slots);
    },
  });
}

/**
 * 将路径字符串转换为 PascalCase 格式的类名
 * @param path 输入的路径字符串，例如 "system/user/index"
 * @returns 转换后的 PascalCase 字符串，例如 "SystemUserIndex"
 */
export function pathToPascalCase(path: string): string {
  // 移除路径开头和结尾的斜杠
  const cleanedPath = path.replace(/^\/+|\/+$/g, "");

  // 按斜杠分割路径
  const segments = cleanedPath.split("/");

  // 将每个段转换为 PascalCase 并合并
  return segments
    .map((segment) => {
      // 处理可能包含特殊字符的段，如 "user-profile"
      const words = segment
        .replace(/[^a-zA-Z0-9]+/g, " ") // 替换非字母数字字符为空格
        .split(" ")
        .filter((word) => word.length > 0);

      // 将每个单词转换为 PascalCase
      return words
        .map(
          (word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(),
        )
        .join("");
    })
    .join("");
}

/** 添加Webpack模块菜单. **/
//const modules = require.context("@/views", true, /\.vue$/);
export function addWebpackMenus(modules: any, startLen: number) {
  modules.keys().forEach((path: string) => {
    menus.set(
      path.substring(startLen, path.length - 4),
      modules(path).default || modules(path),
    );
  });
}

/** 添加动态路由. */
export function addDynamicRoute(routes: RouteRecordRaw[]) {
  dynamicRoutes.push(...routes);
}

/** 更新环境配置. */
export function updateMetaEnv(metaEnv: VueMetaEnv) {
  Object.assign(vueMetaEnv, metaEnv);
  imageUrl = `${vueMetaEnv.APP_API_URL}v1/file/path/pc`;
  return vueMetaEnv;
}

/** 更新Vite环境配置. */
export function updateViteMetaEnv(viteMetaEnv: ImportMetaEnv): VueMetaEnv {
  const metaEnv: VueMetaEnv = convertViteMetaEnv(viteMetaEnv);
  return updateMetaEnv(metaEnv);
}

/** 更新Webpack环境配置. */
export function updateWebpackMetaEnv(webpackMetaEnv: any): VueMetaEnv {
  const metaEnv: VueMetaEnv = convertWebpackMetaEnv(webpackMetaEnv);
  return updateMetaEnv(metaEnv);
}

/** 转换Vite环境配置. */
export function convertViteMetaEnv(viteMetaEnv: ImportMetaEnv): VueMetaEnv {
  if (viteMetaEnv == undefined) {
    return {} as VueMetaEnv;
  }
  const metaEnv: VueMetaEnv = Object.keys(viteMetaEnv)
    .filter((key) => key.startsWith("VITE_APP_"))
    .reduce((acc: VueMetaEnv, key) => {
      const shortKey = key.replace(/^VITE_/, "");
      return Object.assign(acc, { [shortKey]: viteMetaEnv[key] });
    }, {} as VueMetaEnv);

  return metaEnv;
}

/** 转换Webpack环境配置. */
export function convertWebpackMetaEnv(webpackMetaEnv: any): VueMetaEnv {
  if (webpackMetaEnv == undefined) {
    return {} as VueMetaEnv;
  }
  const metaEnv: VueMetaEnv = Object.keys(webpackMetaEnv)
    .filter((key) => key.startsWith("VUE_APP_"))
    .reduce((acc: VueMetaEnv, key) => {
      const shortKey = key.replace(/^VUE_/, "");
      return Object.assign(acc, { [shortKey]: webpackMetaEnv[key] });
    }, {} as VueMetaEnv);

  return metaEnv;
}

/** 更新系统配置信息. */
export function updateSettings(setting: AppSettings) {
  return Object.assign(defaultSettings, setting);
}

//CSS Image Var
export function cssImageVar(css: string, image: string, url: boolean = true) {
  const fullUrl = url ? `url('${imageUrl}${image}')` : `${imageUrl}${image}`;
  document.documentElement.style.setProperty(css, fullUrl);
}
export { vueMetaEnv, menus, defaultSettings, dynamicRoutes, imageUrl };

export default defaultSettings;
